# -*- coding: utf-8 -*-
from __future__ import unicode_literals
import xadmin
from .MyIO import *
from .MySqlite import *

config_file_patch = "/usr/local/freeswitch/conf/"
getcwd="/var/www/MyIPPbx"
class SipProAdmin(object):
    list_display = ['name','IP','proxy']
    list_per_page = 10
    add_form_template = 'myform.html'
    change_form_template = 'myform.html'
    xadmin.views.edit.UpdateAdminView.exclude = ['name']
    def valid_forms(self):
        #strData = str(self.form_obj.data).replace(" u'_save': [u''],", '').split(',')
        ip = self.form_obj.data["IP"]
        if len(ip.split('.')) <> 4:
            self.message_user(u'错误,IP格式错误(192.168.1.85)!', 'error')
        else:
            return self.form_obj.is_valid()

    def save_models(self):
        obj = self.new_obj
        self.new_obj.save()
        urllist = str(self.request.get_full_path()).split('/')
        if len(urllist) == 5:
            WriteGW(obj,"SELECT * from pbx_sippro")
        else:
            WriteGW(obj, "SELECT * from pbx_sippro WHERE id<>"+urllist[3])
        self.message_user(u'告警,请重启IPPBX!', 'warning')


    def delete_models(self, obj):
        obj.delete()
        UpdateGW("select * from pbx_sippro ORDER BY id desc")
        self.message_user(u'告警,请重启IPPBX!', 'warning')

def UpdateGW(strsql):
    info = ReadFile(os.path.join(getcwd+"/pbx/tpl",'gw1.xml'))
    strcontent = ""
    aclList = ReadSql(strsql)
    for i in aclList:
        strcontent += info.replace('{name}', i[1]).replace("{proxy}",i[2]+":"+str(i[3])).replace("{realm}",i[2])+"\r\n"
    WriteFile(config_file_patch+"sip_profiles/external/mysip.xml", strcontent)


def WriteGW(obj,strsql):
    info = ReadFile(os.path.join(getcwd+"/pbx/tpl",'gw1.xml'))
    strcontent = info.replace('{name}', obj.name).replace("{proxy}",obj.IP+":"+str(obj.proxy)).replace("{realm}",obj.IP)+"\r\n"
    aclList = ReadSql(strsql)
    for i in aclList:
        strcontent += info.replace('{name}', i[1]).replace("{proxy}",i[2]+":"+str(i[3])).replace("{realm}",i[2])+"\r\n"
    WriteFile(config_file_patch+"sip_profiles/external/mysip.xml", strcontent)

